import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
    {
        path: '/login',
        name: 'login',
        component: () => import('../views/login/LoginView.vue')
    },
    {
        path: '/ModuleMain',
        name: 'ModuleMain',
        component: () => import('../text/views/ModuleMain.vue')
    },
    {
        path: '/Home',
        name: 'Home',
        component: () => import('../views/HomePage.vue')
    },{
        path: '/home1',
        name: 'home1',
        component: () => import('../views/homePage/home.vue')
    }
]

const router = new VueRouter({
    // 取消#号
    mode: 'history',
    routes
})
router.beforeEach((to, from, next) => {
    const isAuthenticated = localStorage.getItem('token'); // 检查用户是否已登录
    if (to.path === '/') {
        next('/Home')
    }
    console.log("访问地址是" + to.path + " token是" + isAuthenticated)
    if (to.path !== '/login' && !isAuthenticated) { // 如果用户未登录且访问的不是登录页面
        next('/login'); // 重定向到登录页面
    } else {
        next(); // 放行
    }
});

const token = localStorage.getItem('jwt'); // 假设token存储在localStorage中

// token校验
// fetch('https://api.example.com/protected-resource', {
//     method: 'GET',
//     headers: {
//         'Authorization': `Bearer ${token}` // 将token放在Authorization头中
//     }
// })
//     .then(response => {
//         if (response.status === 200) {
//             return response.json();
//         } else if (response.status === 401) {
//             // 处理身份验证失败的情况
//             throw new Error('身份验证失败，请重新登录');
//         } else {
//             throw new Error('请求失败');
//         }
//     })
//     .then(data => {
//         // 处理成功获取的数据
//     })
//     .catch(error => {
//         // 处理错误情况，如显示错误消息给用户
//     });

export default router
